//以下是递归算法
#include "stdafx.h"
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<assert.h>
#include<vector>
#include<fstream>
#include<queue>
using namespace std;
struct Tree
{
Tree(char value)
{
pLeft=pRight=NULL;
this->value=value;
//distance=depth=0;
}
Tree *pLeft,*pRight;
char value;
//int distance;
//int depth;
};
void CreateTree(Tree *&T,int &index)
{// 以# 代替空
// A B D H # # # E # # C F # I # # G # #
//A B D F H # # # G # I # # E # # C # #
ifstream in;
in.open("Tree.txt");
in.seekg(index*2);
index++;
char value;
in>>value;
//std::cout<<value<<" ";
if(value=='#')
T=NULL;
else
{
T=new Tree(value);
CreateTree(T->pLeft,index);
CreateTree(T->pRight,index);
}
in.clear();
in.close();
}
void DestroyTree(struct Tree*&T)
{
if(T)
{
DestroyTree(T->pLeft);
DestroyTree(T->pRight);
delete T;
}
}
void LevelOrderTraverse(struct Tree*&T)
{
std::cout<<std::endl<<"----------------------中序遍历二叉树结构------------------"<<std::endl;
std::queue<Tree*>Q;
Q.push(T);
while(!Q.empty())
{
Tree *tempT=Q.front();
Q.pop();
if(tempT)
{
std::cout<<tempT->value<<" ";
Q.push(tempT->pLeft);
Q.push(tempT->pRight);
}
else
{
std::cout<<"#"<<" ";
}
}
std::cout<<std::endl<<"-----------------------------------------------------------"<<std::endl;
}
void ComputeMaxDistance(Tree* &T,int &dis,int&depth)
{
dis=0;
depth=0;
if(T)
{
int rDis=0,lDis=0,lDepth=0,rDepth=0;
ComputeMaxDistance(T->pLeft,lDis,lDepth);
ComputeMaxDistance(T->pRight,rDis,rDepth);
depth=max(lDepth,rDepth)+1;
dis=max(2+rDepth+lDepth,max(lDis,rDis));
}
else
{
depth=-1;
}
}
void RunAlgorithm()
{
Tree *T;int index=0;
CreateTree(T,index);
LevelOrderTraverse(T);
int maxDepth,maxDis;
ComputeMaxDistance(T,maxDis,maxDepth);
std::cout<<"maxDis:"<<maxDis<<" maxDepth:"<<maxDepth<<std::endl;
DestroyTree(T);
}
//以下主函数
int _tmain(int argc, _TCHAR* argv[])
{
RunAlgorithm();
system("pause");
return 0;
}
扩展问题:
非递归算法就是后续遍历的非递归算法而已